﻿//**********************************************************
//Copyright(C)2010 By 波特商网公司 版权所有。
//
//文件名：LoginForm.cs
//文件功能：登录窗口
//
//创建标识：齐李平 || 2011-03-24
//
//修改标识：
//修改描述：
//**********************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Hmc.IM.Common;
using Hmc.IM.Common.Base;
using Hmc.IM.Client.Core;
using Hmc.IM.Client.Properties;
using System.Net;
using System.Net.Sockets;
using System.Text;


namespace Hmc.IM.Client
{
    /// <summary>
    /// 登录Form
    /// </summary>
    public partial class LoginForm : Form
    {
        #region 移动窗体相关事件

        private const int WM_NCLBUTTONDOWN = 0xA1;
        private const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginForm()
        {
            InitializeComponent();
            this.BackColor = Color.Yellow;
            this.TransparencyKey = this.BackColor;
            this.panelTop.MouseDown += new MouseEventHandler(panelTop_MouseDown);
            this.panelTop.MouseMove += new MouseEventHandler(panelTop_MouseMove);
            this.panelTop.MouseUp += new MouseEventHandler(panelTop_MouseUp);
            this.lblTitle.MouseDown += new MouseEventHandler(panelTop_MouseDown);
            this.lblTitle.MouseMove += new MouseEventHandler(panelTop_MouseMove);
            this.lblTitle.MouseUp += new MouseEventHandler(panelTop_MouseUp);
        }

        #region 窗体移动事件
        private bool isMouseDown = false;
        private Point FormLocation;     //form的location
        private Point mouseOffset;      //鼠标的按下位置

        void panelTop_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }

        void panelTop_MouseMove(object sender, MouseEventArgs e)
        {
            int _x = 0;
            int _y = 0;
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                _x = mouseOffset.X - pt.X;
                _y = mouseOffset.Y - pt.Y;

                this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
            }
        }

        void panelTop_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //isMouseDown = true;
                //FormLocation = this.Location;
                //mouseOffset = Control.MousePosition;
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }
        #endregion

        #region PBCLOSE鼠标事件
        private void pbClose_MouseEnter(object sender, EventArgs e)
        {
            pbClose.Image = Resources.login_x_;
        }

        private void pbClose_MouseLeave(object sender, EventArgs e)
        {
            pbClose.Image = Resources.login_x;
        }
        #endregion

        #region 关闭事件
        private void pbClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        #region PBMin鼠标事件
        private void pbMin_MouseEnter(object sender, EventArgs e)
        {
            pbMin.Image = Resources.login_min_current;
        }

        private void pbMin_MouseLeave(object sender, EventArgs e)
        {
            pbMin.Image = Resources.login_min;
        }
        #endregion

        #region 最小化
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        #endregion

        #region 窗体初始化事件
        /// <summary>
        /// 窗体加载事件（）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginForm_Load(object sender, EventArgs e)
        {
            #region 去除系统默认边框
            Rectangle clientRectangle = ClientRectangle;
            Point clientPoint = PointToScreen(new Point(0, 0));
            clientRectangle.Offset(clientPoint.X - Left, clientPoint.Y - Top);
            Region = new Region(clientRectangle);
            #endregion

            this.Text = CommonTools.SoftName + CommonTools.SoftVersion;
            lblTitle.Text = CommonTools.SoftName + CommonTools.SoftVersion;

#if DEBUG
            txtUserName.Text = "tazij123";
            txtPassword.Text = "123456";
#endif

#if DEBUG
            // lblLoginHint.Text = "正在检测更新，请稍后...";
            //btnLogin.Enabled = false;
            //Utility.BackgroundWorker<bool>(() =>
            //    {
            //        return Core.UpdateHelper.CheckUpdate();
            //    },
            //    (result) =>
            //    {
            //        if (result is bool && (bool)result == true)
            //        {
            //            lblLoginHint.Text = "检测到有新版本，启动更新";
            //            try
            //            {
            //                System.Diagnostics.Process.Start("Newborn.StoreUpdate.exe");//启动更新程序
            //            }
            //            catch (Exception ex)
            //            {
            //                //Recorder.Write(ex);
            //            }
            //        }
            //        else
            //        {
            //            lblLoginHint.Text = "无需更新";
            //            btnLogin.Enabled = true;
            //        }
            //    }
            //    );
#endif
            //lblLoginHint.Text = "";
        }

        /// <summary>
        /// 窗体Activated事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginForm_Activated(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                txtUserName.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                txtPassword.Focus();
                return;
            }

            btnLogin.Focus();
        }
        #endregion

        /// <summary>
        /// 设置按钮的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetting_Click(object sender, EventArgs e)
        {
            LoginSettingForm frm = new LoginSettingForm();
            frm.ShowDialog();
        }

        /// <summary>
        /// 登录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                lblLoginHint.Text = Resources.Msg_Login_UserNameCanNotEmpty;
                txtUserName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                lblLoginHint.Text = Resources.Msg_Login_PasswordCanNotEmpty;
                txtPassword.Focus();
                return;
            }

            #region 禁用登录按钮
            btnLogin.Enabled = false;
            txtUserName.Enabled = false;
            txtPassword.Enabled = false;
            //btnSetting.Enabled = false;
            //lblLoginHint.Text = "正在登录，请稍候...";
            txtPassword.KeyDown -= txtPassword_KeyDown;
            #endregion

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            string userInfo = txtUserName.Text.Trim() + "," + txtPassword.Text;
            worker.RunWorkerAsync(userInfo);
        }

        /// <summary>
        /// 写入委托
        /// </summary>
        /// <param name="msg"></param>
        delegate void WriteLog(string msg);

        /// <summary>
        /// 写入登陆信息
        /// </summary>
        /// <param name="msg">输出信息</param>
        private void SetLoginText(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new WriteLog(SetLoginText), msg);
            }
            else
            {
                lblLoginHint.Text = msg;
            }
        }


        #region 登录线程工作

        /// <summary>
        /// 登录线程处理完毕执行方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result is Exception)
            {
                txtUserName.Enabled = true;
                txtPassword.Enabled = true;
                btnLogin.Enabled = true;
                btnLogin.Focus();
                lblLoginHint.Text = ((Exception)e.Result).Message;
                MessageBox.Show(((Exception)e.Result).Message);
                txtPassword.KeyDown += txtPassword_KeyDown;

                Logger.Write((Exception)e.Result);
                //LoginErrorForm errorForm = new LoginErrorForm();
                //errorForm.Tag = ((Exception)e.Result).Message;
                //errorForm.ShowDialog();
            }
            else if (e.Result is bool && (bool)e.Result)
            {
                MainForm mainFrm = new MainForm();
                mainFrm.Show();
                //Logger.Write(LogType.INFO, "登录成功");
                this.Hide();
            }
            BackgroundWorker worker = sender as BackgroundWorker;
            worker.Dispose();
        }
        private static byte[] receiveResult = new byte[1024];
        private static int serverProt = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ServerPort"]);   //端口  
        private static string serverIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"];   //端口  

        /// <summary>
        /// 登录线程工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string userInfo = e.Argument as string;
            try
            {
                List<int> roleList = new List<int>();//权限列表
                SetLoginText("正在进行服务器验证...");
                Logger.Write(LogType.INFO, userInfo.Split(',')[0] + "开始登录");
                //设定服务器IP地址  
                IPAddress socketServerIP = IPAddress.Parse(serverIP);
                PublicVal.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //try
                //{

                PublicVal.clientSocket.Connect(new IPEndPoint(socketServerIP, serverProt)); //配置服务器IP与端口 

                #region 发送数据
                //发送登录请求，发送的数据：类型|用户名，密码，IP
                PublicVal.clientSocket.Send(Encoding.ASCII.GetBytes((int)EnumDirectiveType.Login + "|" + userInfo + "," + CommonTools.GetLocalIP()));
                #endregion

                #region 接收数据
                int receiveNumber = PublicVal.clientSocket.Receive(receiveResult);
                string resultStr = Encoding.ASCII.GetString(receiveResult, 0, receiveNumber);

                CommandResultEntity result = CommandBusiness.Execute(resultStr);
                if (result.Result == false)
                {
                    if (result.Message == "UserNotExist")
                    {
                        Logger.Write(LogType.INFO, userInfo.Split(',')[0] + "：验证失败，该用户不存在！");
                        throw new Exception("验证失败，该用户不存在！");
                    }
                    else if (result.Message == "PasswordError")
                    {
                        Logger.Write(LogType.INFO, userInfo.Split(',')[0] + "：验证失败，用户密码错误！");
                        throw new Exception("验证失败，用户密码错误！");
                    }

                }
                else
                {
                    LoginUserEntity.UserName = userInfo.Split(',')[0];
                    LoginUserEntity.Password = userInfo.Split(',')[1];
                    LoginUserEntity.IP = CommonTools.GetLocalIP();
                    LoginUserEntity.AccessToken = result.Message;
                    Logger.Write(LogType.INFO, userInfo.Split(',')[0] + "登录成功");
                }
                //Console.WriteLine("接收客户端{0}消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)); 
                #endregion


                e.Result = true;

                //添加登录成功日志
                //Logger.Write("EnumSystemIdentify.Store", userEntity.SystemUserId.ToString(), userEntity.UserName, "用户登录", "用户登录成功");
            }
            catch (Exception ex)
            {
                e.Result = ex;
                //添加登录异常日志
                //Recorder.Write(ex);
            }
        }

        #endregion

        #region 用户名密码文本框回车事件
        /// <summary>
        /// 用户名文本框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (string.IsNullOrEmpty(txtUserName.Text))
                {
                    //用户名不能为空
                    lblLoginHint.Text = Resources.Msg_Login_UserNameCanNotEmpty;
                    txtUserName.Focus();
                }
                else
                {
                    if (!string.IsNullOrEmpty(txtPassword.Text)) btnLogin_Click(this, null);
                    else txtPassword.Focus();
                }
            }
            else
            {
                lblLoginHint.Text = "";
            }
        }

        /// <summary>
        /// 密码文本框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (string.IsNullOrEmpty(txtPassword.Text))
                {
                    //密码不能为空
                    lblLoginHint.Text = Resources.Msg_Login_PasswordCanNotEmpty;
                    txtPassword.Focus();
                }
                else
                {
                    btnLogin_Click(this, null);
                    btnLogin.Focus();
                }
            }
            else
            {
                lblLoginHint.Text = "";
            }
        }
        #endregion
    }
}
